package com.fessc.develop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fessc.develop.entity.dbvo.TOrgConfig;
import com.fessc.develop.mapper.TOrgConfigMapper;
import com.fessc.develop.service.interfaces.ITOrgConfigService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fessc.develop.utils.BusiUtil;
import com.fessc.develop.utils.ExceptionUtil;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author y
 * @since 2024-06-28
 */
@Service
public class TOrgConfigServiceImpl extends ServiceImpl<TOrgConfigMapper, TOrgConfig> implements ITOrgConfigService {

    private Map<String, TOrgConfig> orgConfigMap;

    @Resource
    private TOrgConfigMapper orgConfigMapper;

    @PostConstruct
    void init() {
        List<TOrgConfig> orgConfigList = this.list();
        if (BusiUtil.isNotNull(orgConfigList)) {
            orgConfigMap = orgConfigList.stream().collect(Collectors.toMap(TOrgConfig::getOrgCode, p -> p, (v1, v2) -> v1));
        } else {
            orgConfigMap = new HashMap<>();
        }

    }

    /**
     * 根据机构编号，查询机构信息
     *
     * @param orgCode 机构编号
     * @return 机构信息
     */
    @Override
    public TOrgConfig getOrgConfigByOrgCode(String orgCode) {
        TOrgConfig tOrgConfig = orgConfigMap.get(orgCode);
        if (BusiUtil.isNull(tOrgConfig)) {
            QueryWrapper<TOrgConfig> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("org_code", orgCode);
            tOrgConfig = this.getOne(queryWrapper);

            if (BusiUtil.isNull(tOrgConfig)) {
                throw ExceptionUtil.businessException("EE1002");
            }
        }
        return tOrgConfig;
    }

    /**
     * 根据机构编号、互市点编码和平台编码，查询机构信息
     *
     * @param orgCode           机构编号
     * @param exchangePlaceCode 互市点编码
     * @param platid_s          平台编码
     * @return 机构信息
     */
    @Override
    public List<TOrgConfig> getOrgConfigByCodePlatid(String orgCode, String exchangePlaceCode, String platid_s) {
        QueryWrapper<TOrgConfig> queryWrapper = new QueryWrapper<>();
        if (BusiUtil.isNotNull(orgCode)) {
            queryWrapper.eq("org_code", orgCode);
        }
        if (BusiUtil.isNotNull(exchangePlaceCode)) {
            queryWrapper.eq("exchange_place_code", exchangePlaceCode);
        }
        if (BusiUtil.isNotNull(platid_s)) {
            queryWrapper.eq("platid_s", platid_s);
        }
        return this.list(queryWrapper);
    }

    /**
     * 查询机构信息
     *
     * @param paymentType 支付类型
     * @return 机构信息
     */
    @Override
    public List<TOrgConfig> getOrgConfigByPaymentType(String paymentType) {
        return orgConfigMapper.getOrgConfigByPaymentType(paymentType);
    }

}
